package de.lmu.mvs.lerngruppenfinder.utils;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.json.JSONException;
import org.json.JSONObject;

import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.eclipsesource.json.ParseException;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.AvoidXfermode.Mode;
import android.util.Log;

/**
 * Some functions for writing and reading app data to the storage
 * 
 * @author Christopher Gebhardt
 *
 */
public class FileApi {

	private static final String TAG = FileApi.class.getSimpleName();

	public static final String LOGIN_PREFERENCES = "loginPrefs";
	public static final String LOGIN_NAME = "loginName";
	public static final String LOGIN_EMAIL = "loginEmail";
	public static final String LOGIN_PASSWORD = "loginPassword";
	public static final String LOGIN_ID = "id";
	public static final String TIMESTAMP = "loginTimestamp";

	public static final long MAX_STORAGE_TIME = 1000 * 60 * 60 * 2;

	/**
	 * Store Login Credentials in SharedPreferences
	 * 
	 * @param name
	 * @param email
	 * @param password
	 */
	public static void storeLoginCredentials(String name, String email, String password, int id){
		SharedPreferences loginPreferences = ApplicationController.getInstance()
				.getSharedPreferences(LOGIN_PREFERENCES, Context.MODE_PRIVATE);

		loginPreferences.edit().putString(LOGIN_NAME, name).commit();
		loginPreferences.edit().putString(LOGIN_EMAIL, email).commit();
		loginPreferences.edit().putString(LOGIN_PASSWORD, password).commit();
		loginPreferences.edit().putInt(LOGIN_ID, id).commit();
		loginPreferences.edit().putLong(TIMESTAMP, System.currentTimeMillis()).commit();
	}

	public static void deleteLoginCredentials(){
		SharedPreferences loginPreferences = ApplicationController.getInstance()
				.getSharedPreferences(LOGIN_PREFERENCES, Context.MODE_PRIVATE);

		loginPreferences.edit().putString(LOGIN_NAME, null).commit();
		loginPreferences.edit().putString(LOGIN_EMAIL, null).commit();
		loginPreferences.edit().putString(LOGIN_PASSWORD, null).commit();
		loginPreferences.edit().putInt(LOGIN_ID, 0).commit();
		loginPreferences.edit().putLong(TIMESTAMP, System.currentTimeMillis()).commit();
	}

	/**
	 * FIXME for now it only checks whether someone is logged in or not
	 * 
	 * @return null if there are no credentials saved or the userCredetentials
	 */
	public static UserCredentials readLoginCredentials(){
		SharedPreferences loginPreferences = ApplicationController.getInstance()
				.getSharedPreferences(LOGIN_PREFERENCES, Context.MODE_PRIVATE);

		String name = loginPreferences.getString(LOGIN_NAME, null);
		String mail = loginPreferences.getString(LOGIN_EMAIL, null);
		String password = loginPreferences.getString(LOGIN_PASSWORD, null);
		int id = loginPreferences.getInt(LOGIN_ID, 0);

		if(name != null && mail != null && password != null && id != 0){
			return new UserCredentials(name, mail, id, password);
		} else {
			return null;
		}
	}

	public static void writeToStorage(String content, String fileName, Context context) throws IOException {
		FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
		fos.write(content.getBytes());
		fos.close();
	}

	/**
	 * Write a json file to storage
	 * @param json
	 * @param fileName
	 * @param context
	 * @throws IOException
	 */
	public static void writeJsonToStorage(JsonValue json, String fileName, Context context) throws IOException{
		// add timestamp to tag data
		JsonObject fileObject = new JsonObject();
		fileObject.add("timestamp", System.currentTimeMillis());
		fileObject.add("data", json);

		writeToStorage(fileObject.toString(), fileName, context);
	}

	/**
	 * @param fileName
	 * @param context
	 * @return json from storage or null
	 */
	public static JsonValue readJsonFromStorage(String fileName, Context context){
		JsonValue json = null;

		FileInputStream fis;
		try {
			fis = context.openFileInput(fileName);

			json = JsonValue.readFrom(new BufferedReader(new InputStreamReader(fis)));

			JsonValue jsonTimeStamp = json.asObject().get("timestamp");
			long time = Long.parseLong(jsonTimeStamp.toString());

			// dont return null if of the type:
			if(fileName.equals("actualEvent") || fileName.equals("UserCredentials")){
				json = json.asObject().get("data");
			} else {
				if(System.currentTimeMillis() - time > MAX_STORAGE_TIME){
					return json = null;
				} else {
					json = json.asObject().get("data");
				}
			}

		} catch (FileNotFoundException e) {
			Log.w(TAG, "Could not get json from storage.");
			json = null;
		} catch (IOException e) {
			Log.w(TAG, "Could not get json from storage.");
			json = null;
		} catch (ParseException e) {
			Log.w(TAG, "File content is not a json string. ");
			json = null;
		} catch (UnsupportedOperationException e) {
			Log.w(TAG, "File is not a valid JsonValue");
			json = null;
		}
		return json;
	}

	public static class UserCredentials {

		public String name = null;
		public String mail = null;
		public String password = null;
		public int id = 0;

		public UserCredentials(String name, String mail, int id, String password){
			this.name = name;
			this.mail = mail;
			this.id = id;
			this.password = password;
		}

	}
}

